<!-- 订单发货 OrderDelivery -->
<template>
  <div class="content">

    <div class="delivery" v-loading="loading">
      <div class="delivery-list">
        <h3>
          订单商品
          <!-- <el-link type="primary" @click="onClearLogInfo">清除物流信息</el-link> -->
        </h3>
        <el-table :data="tableList" ref="deliveryTableData" border fit @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :selectable="handleDisable"></el-table-column>
          <el-table-column prop="name" label="商品" align="center" min-width="200px">
            <template slot-scope="scope">
              <div class="product">
                <div class="product-img">
                  <el-image class="product-img-small" fit="contain" :src="scope.row.productPic"></el-image>
                </div>
                <div class="product-word">
                  <span>{{scope.row.productName}}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="订单编号" align="center" min-width="130px">
            <template slot-scope="scope">
              {{scope.row.orderSn || orderData.orderSn}}
            </template>
          </el-table-column>
          <el-table-column prop="productPrice" label="商品价格" align="center"></el-table-column>
          <el-table-column prop="" label="商品规格" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.sp1 ? scope.row.sp1:''}}{{scope.row.sp2 ? ',' + scope.row.sp2 : ''}}{{scope.row.sp3 ?
                ',' + scope.row.sp3: ''}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="realAmount" label="付款价格" align="center"></el-table-column>
          <el-table-column prop="productIntegration" label="积分价格" align="center"></el-table-column>
          <el-table-column prop="productQuantity" label="数量" align="center" min-width="70px"></el-table-column>
          <el-table-column prop="productPrice" label="金额小计" align="center" min-width="110px">
            <template slot-scope="scope">
              <div>
                金额：{{(scope.row.realAmount * scope.row.productQuantity) || 0}} <br />
                积分：{{(scope.row.productIntegration * scope.row.productQuantity) || 0}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" min-width="100px">
            <template slot-scope="scope">
              <span v-if="scope.row.deliveryNo && scope.row.deliveryNo > 0">
                <span>已发货</span>
                <el-tooltip :content="'包裹' + scope.row.deliveryNo" placement="top">
                  <span style="margin: 0 5px;">{{scope.row.deliveryNo}}</span>
                </el-tooltip>
              </span>
              <span v-else>待发货</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="delivery-list delivery-con">
        <div class="receiver-con">
          <h3>订单收货信息</h3>
          <div class="receiver">
            <p>收货人： <span>{{orderData.receiverName}}</span></p>
            <p>收货电话： <span>{{orderData.receiverPhone}}</span></p>
            <p>收货地址： <span>{{orderData.address}}</span></p>
          </div>
        </div>
        <div class="delivery-info">
          <h3>物流信息</h3>
          <el-form :model="expressData" ref="deliveryForm" size="medium" :rules="rules" label-width="100px">
            <el-form-item label="快递公司：" prop="deliveryCompany">
              <el-select class="c-select" v-model="expressData.deliveryCompany" placeholder="请选择快递公司" clearable>
                <el-option v-for="item in logistics" :key="item.label" :label="item.label + ' (' +item.value +')'"
                           :value="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="快递单号：" prop="deliverySn">
              <el-input v-model="expressData.deliverySn" placeholder="请输入快递单号"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="delivery-list">

      </div>
      <div class="delivery-list">
        <Cbutton type="" size="medium" @click="handleCancle">取 消</Cbutton>
        <Cbutton size="medium" :btnloading="btnLoading" @click="doDeliveryOrder('deliveryForm')">确 定</Cbutton>
      </div>
    </div>

  </div>
</template>
<script>
import { orderSendFormRules } from '@/utils/rules'
import { GetOrderDetail, SendOrder, SendSubpackageOrder, ClearSubpackageOrder } from '@/api/order'
import { mapGetters } from 'vuex'

export default {
  name: 'OrderDelivery',
  props: {},
  data () {
    return {
      loading: false,
      orderId: '',
      packageNum: '', // 包裹名
      tableList: [],
      selectionList: [],
      orderData: {},
      expressData: {
        orderId: '',
        deliveryCompany: '',
        deliverySn: ''
      },
      sendCount: 0, // 发货几次
      btnLoading: false,
      rules: orderSendFormRules
    }
  },
  computed: {
    ...mapGetters([
      'logistics'
    ])
  },
  watch: {
  },
  created () {
    this.orderId = this.$route.query.id
    this.packageNum = this.$route.query.pnum || ''
    this.expressData.orderId = this.orderId
    this.getDetail()
  },
  mounted () {
    if (!this.logistics || this.logistics.length <= 0) {
      this.$store.dispatch('getLogistics')
    } else {
      this.$store.dispatch('getLogistics')
    }
  },
  methods: {
    getDetail () {
      this.loading = true
      GetOrderDetail(this.orderId).then(res => {
        const data = res.data
        this.tableList = data.itemList || []
        this.orderData = data.omsOrder || {}

        // 判断订单是否已经发完商品
        if (this.sendCount > 0) {
          this.handleSendProductAll()
        } else {
          this.sendCount++
        }

        this.orderData.address = data.omsOrder.receiverProvince + data.omsOrder.receiverCity + data.omsOrder.receiverRegion + ' ' + data.omsOrder.receiverDetailAddress
        // 设置默认选中表格数据
        this.handleCheckData()
        // 设置禁用选择表格数据
        this.handleDisable()

        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    // 选择表格数据
    handleSelectionChange (selection) {
      this.selectionList = selection
    },
    // 修改订单物流 有包裹名 进行设置 默认选中表格
    handleCheckData () {
      if (this.packageNum) {
        this.tableList.forEach(item => {
          const deliveryNo = typeof item.deliveryNo === 'string' ? item.deliveryNo : item.deliveryNo.toString()
          if (deliveryNo === this.packageNum) {
            this.expressData.deliverySn = item.deliverySn
            this.expressData.deliveryCompany = item.deliveryCompany
            this.$nextTick(() => {
              this.$refs.deliveryTableData && this.$refs.deliveryTableData.toggleRowSelection(item, true)
            })
          }
        })
      }
    },
    // 函数需要一个返回值,true为可选,false为不可选择 禁止表格某行不可选择
    handleDisable (row, index) {
      const deliveryNo = typeof row.deliveryNo === 'string' ? row.deliveryNo : row.deliveryNo.toString()
      if (this.packageNum) {
        if (deliveryNo === this.packageNum) {
          return true
        } else {
          return false
        }
      } else {
        return row.deliveryNo <= 0
      }
    },

    onClearLogInfo () {
      const tips = `确定清除所有的物流信息吗？`
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearLogApi()
      }).catch(() => { })
    },
    doDeliveryOrder (formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        this.btnLoading = true
        // 是否勾选全部
        if (this.selectionList.length <= 0) {
          this.$message.warning('请选择订单商品')
          this.btnLoading = false
        } else if (this.selectionList.length === this.tableList.length) {
          this.sendOrderAllPackage(this.expressData)
        } else {
          let params = JSON.parse(JSON.stringify(this.expressData))
          params.itemIds = []
          this.selectionList.forEach(item => {
            params.itemIds.push(item.id)
          })
          this.sendOrderPackage(params)
        }
      })
    },
    // 分包发或者修改
    sendOrderPackage (params) {
      let param = params || {}
      SendSubpackageOrder(param).then(res => {
        this.$message.success(res.message || '发货成功')
        this.clearExpressData()
        this.getDetail()
        this.btnLoading = false
      }).catch(e => {
        this.btnLoading = false
      })
    },
    // 整个订单发或者修改
    sendOrderAllPackage (params) {
      SendOrder(params).then(res => {
        this.$message.success(res.message || '发货成功')
        this.clearExpressData()
        this.getDetail()
        this.btnLoading = false
      }).catch(e => {
        this.btnLoading = false
      })
    },
    // 整个订单清除物流信息
    clearLogApi () {
      const params = { orderId: this.orderId }
      ClearSubpackageOrder(params).then(res => {
        this.$router.go(-1)
        this.$message.success(res.message || '清除成功')
      }).catch(e => { })
    },
    // 清除物流表单信息
    clearExpressData () {
      this.expressData.deliveryCompany = ''
      this.expressData.deliverySn = ''
      this.$refs.deliveryForm.resetFields()
    },
    handleCancle () {
      this.$router.go(-1)
    },
    // 判断订单是否已经发完商品
    handleSendProductAll () {
      let count = 0 // 大于0 商品未发完
      setTimeout(() => {
        this.tableList.forEach(v => {
          if (v.deliveryNo === 0) {
            count++
          }
        })
        if (count === 0) {
          this.$router.push({ name: 'pms:order:detail', query: { id: this.orderId } })
        }
      }, 100)
    }

  }
}
</script>

<style scoped lang='scss'>
.delivery {
  padding: 0 40px 20px;
  .delivery-con {
    display: flex;
    justify-content: flex-start;
    flex-flow: row;
    margin: 10px 0;
  }
  .receiver-con {
    width: 500px;
  }
}
.delivery-list {
  .receiver {
    p {
      line-height: 30px;
    }
  }
  form {
    width: 300px;
  }
  h3 {
    margin: 10px 0;
    font-size: 20px;
    font-weight: bold;
  }
}
</style>
